package com.example.chenling

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class AddStudentActivity : AppCompatActivity() {

    private lateinit var etId: EditText
    private lateinit var etName: EditText
    private lateinit var etGender: EditText
    private lateinit var etClass: EditText
    private lateinit var btnSave: Button
    private lateinit var btnCancel: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_student)

        etId = findViewById(R.id.etId)
        etName = findViewById(R.id.etName)
        etGender = findViewById(R.id.etGender)
        etClass = findViewById(R.id.etClass)
        btnSave = findViewById(R.id.btnSave)
        btnCancel = findViewById(R.id.btnCancel)

        btnSave.setOnClickListener {
            val id = etId.text.toString()
            val name = etName.text.toString()
            val gender = etGender.text.toString()
            val className = etClass.text.toString()

            if (id.isNotEmpty() && name.isNotEmpty() && gender.isNotEmpty() && className.isNotEmpty()) {
                val student = Student(id, name, gender, className)
                val resultIntent = Intent()
                resultIntent.putExtra(EXTRA_STUDENT, student)
                setResult(RESULT_OK, resultIntent)
                finish()
            } else {
                Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show()
            }
        }

        btnCancel.setOnClickListener {
            finish()
        }
    }

    companion object {
        const val EXTRA_STUDENT = "extra_student"
    }
}